package ru.spb.osll.myfit.server.execute;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import ru.spb.osll.myfit.common.ProgressCounts;
import fit.Counts;
import fit.Parse;

public class MyFitFixtureListener  implements ProgressFixtureListener {
	private ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

	public void tableFinished(Parse table) {
		try {
			byte[] bytes = readTable(table);
			if (bytes.length > 0) {
				outputStream.write(bytes);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void tablesFinished(Counts count) {
	}

	private byte[] readTable(Parse table) throws IOException {
		ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
		OutputStreamWriter streamWriter = new OutputStreamWriter(
				byteBuffer, "UTF-8");
		PrintWriter writer = new PrintWriter(streamWriter);
		Parse more = table.more;
		table.more = null;
		if (table.trailer == null)
			table.trailer = "";
		table.print(writer);
		table.more = more;
		writer.close();
		return byteBuffer.toByteArray();
	}

	public String getOutput() {
		return outputStream.toString();
	}

	@Override
	public void countTotalTablesQuantity(Parse tables) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public ProgressCounts getCounts() {
		return new ProgressCounts();
	}

	@Override
	public void setCounts(Counts counts) {
		// TODO Auto-generated method stub
		
	}
}

